import java.io.File;
import java.io.FileOutputStream;

/*
 * This algorithm counts the number of votes in the range 0 to 15
 */
public class UHIST extends Scheduler implements Runnable {
	int start;
	int stop;
	byte[] BLOCK;

	public UHIST(int start, int stop) {
		this.start = start;
		this.stop = stop;
	}

	void writeBlock() {
		String FILE_NAME = BLOCK_PATH + start + ".bin";
		File out = new File(FILE_NAME);
		FileOutputStream fos;
		try {
			fos = new FileOutputStream(out);
			fos.write(BLOCK);
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.print(BLOCK[0] + " ");
		System.out.println("DW: " + FILE_NAME + " @ " + this.getClass());
	}

	@Override
	public void run() {
		int ilen = USERB[0].ilen;
		BLOCK = new byte[(stop - start) * ilen];

		int c = 0;
		for (int bUserID = start; bUserID < stop; bUserID++) {
			for (int i = 0; i < ilen; i++) {
				int bItemID = USERB[bUserID].items[i];

				byte pred = normalize(predict(bUserID, bItemID));
				BLOCK[c * ilen + i] = pred;
			}
			c++;
		}

		writeBlock();
	}

	byte normalize(double count) {
		System.out.println("count: " + count);
		if (count > CUT_OFF) { // x / 100 = 100 // 10000
			double countOverGlobalMax = count / NORMALIZER + CUT_OFF;
			if (countOverGlobalMax > 100) {
				countOverGlobalMax = 100;
			}
			return (byte) countOverGlobalMax;
		} else {
			return (byte) count;
		}
	}

	public double predict(int bUserID, int bItemID) {
		User aUser = USERA[bUserID];
		byte[] votes = aUser.votes;

		double count = 0;
		for (byte vote : votes) {
			if (vote >= LEFT && vote < RIGHT) {
				count++;
			}
		}

		return count;
	}
}